<template>
  <div>
    <div class="app-container">
      <h-table-list
        border
        type="local"
        :page-sizes="[10, 20]"
        :data="system_username.records"
        @size-change="handleSizeChange"
        :columns="columns"
        :paginationInfo="paginationInfo"
        :form-options="formOptions"
      >
        <ListOpearteButton />
        <template slot="userType" slot-scope="scope">
          <p>
            <i v-if="scope.row.userType == 0" class="iconfont deviceicon-dian-0"
              >PC</i
            >
            <i v-if="scope.row.userType == 1" class="iconfont deviceicon-dian-1"
              >手机</i
            >
          </p>
        </template>
        <!-- <template slot="createTime" slot-scope="scope">
          <p>
           {{scope.row.createdTime}}
          </p>
        </template> -->
        <template slot="enable" slot-scope="scope">
          <span v-if="scope.row.enable == 0">
            <div class="circle-14" />
            <span>停用</span>
          </span>
          <span v-if="scope.row.enable == 1">
            <div class="circle-13" />
            <span>启用</span>
          </span>
        </template>
        <template slot="operate-column" slot-scope="scope">
          <tableButton :row="scope.row" />
        </template>
      </h-table-list>
    </div>
    <DownloadIdentify
      @cancel="cancel"
      @update="dialogSubmit"
      :visible.sync="dialogFormVisible"
      title="账号管理"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="姓名" prop="realName">
          <el-input v-model="ruleForm.realName"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="ruleForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="归属部门" prop="organId">
          <el-cascader
            v-model="ruleForm.organId"
            :options="app.allCode.department"
            :props="{ emitPath: false }"
            clearable
          >
          </el-cascader>
        </el-form-item>
        <el-form-item label="职位" prop="positionsId">
          <el-select v-model="ruleForm.positionsId">
            <el-option
              v-for="e in app.allDuty"
              :key="e.value || e"
              :label="e.label || e"
              :value="e.value || e"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="账号类别" prop="userType">
          <el-select v-model="ruleForm.userType" :multiple="true">
            <el-option label="PC" value="0" />
            <el-option label="APP" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="登录账号" prop="userName">
          <el-input v-model="ruleForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="showPwd">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>
      </el-form>
    </DownloadIdentify>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import waves from "@/directive/waves"; // waves directive
import DownloadIdentify from "@/components/FormDialog";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import ListOpearteButton from "@/components/AllButton/button2";
import tableButton from "@/components/AllButton/button3";
import data from "./const";
import { parseTime, listTotree } from "@/utils";
export default {
  name: "system_username",
  components: {
    DownloadIdentify,
    Pagination,
    tableButton,
    ListOpearteButton
  },
  directives: { waves },
  filters: {
    typeFilter(type) {
      return calendarTypeKeyValue[type];
    }
  },
  data() {
    return {
      dialogFormVisible: false,
      loadList: false,
      showPwd: false,
      ruleForm: {
        userName: "",
        userType: "",
        enable: null,
        password: "",
        realName: "",
        phone: "",
        organId: "",

        positionsId: ""
      },
      rules: {
        userName: [
          { required: true, message: "请输入userName", trigger: "blur" },
          {
            min: 6,
            max: 20,
            message: "6-20位，支持英文字母、阿拉伯数字，必须包含2种",
            trigger: "blur"
          }
        ],
        realName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        password: [
          {
            required: true,
            message:
              "密码6-20位，包含字母、数字、符号中至少两种，字母区分大小写",
            trigger: "blur"
          }
        ],
        organId: [{ required: true, message: "请选择", trigger: "blur" }],
        positionsId: [{ required: true, message: "请选择", trigger: "blur" }],
        phone: [
          { required: true, message: "请输入正确手机号", trigger: "blur" }
        ],
        userType: [
          { required: true, message: "请选择账号类别", trigger: "blur" }
        ]
      },

      paginationInfo: {
        sizeChange: e => {
          console.log(e);
        },
        currentChange: e => {
          this.$store.dispatch("system_username/setListSearchParams", {
            current: e
          });
          this.getList(
            Object.assign(
              {},
              this.$store.state.system_username.listSearchParams
            )
          );
        },
        current: 1,
        total: 10
      },
      formOptions: {
        inline: true,
        submitBtnText: "搜索",
        showResetBtn: true,
        searchParamsHandler: () => {
          console.log("搜索");
          this.getList(this.$store.state.system_username.listSearchParams);
        },
        changevalue: params => {
          console.log(params, "++++params+++");
          this.$store.dispatch("system_username/setListSearchParams", params);
        },
        resetBtnCallback: () => {
          this.$store.dispatch("system_username/setListSearchParams", {});
          // this.getList(this.$store.state.system_username.listSearchParams);
          this.getList();
        },
        forms: [
          { prop: "empno", label: "员工编号" },

          { prop: "userName", label: "姓名" },
          { prop: "deviceNumber", label: "手机号" },
          {
            prop: "organId",
            label: "归属部门",
            itemType: "cascader",
            options: [] //this.listTotree(this.$store.state.app.allCode.department),
          },

          {
            prop: "positionsId",
            label: "职位",
            itemType: "select",
            options: [{ value: 0, label: "通用" }, { value: 1, label: "专用" }]
          },
          {
            prop: "userType",
            label: "账号类别",
            itemType: "select",
            options: [
              { value: "0", label: "手机" },
              { value: "1", label: "PC" }
            ]
          }
        ]
      },
      columns: [
        { prop: "empno", label: "员工编号" },

        {
          prop: "realName",
          label: "姓名"
          //width: 100,
          // render: (row) => {
          //   const { deviceInfo } = row;
          //   return deviceInfo.name ? deviceInfo.name :"";
          // },
        },
        {
          prop: "phone",
          label: "手机号"
          //width: 100,
          // render: (row) => {
          //   const { deviceInfo } = row;
          //   return deviceInfo.deviceNumber ? deviceInfo.deviceNumber :"";
          // },
        },
        // { prop: "departmentName", label: "使用部门", minWidth: 180, render: (row) => {
        //     const { departmentInfo } = row;
        //     return departmentInfo.name ? departmentInfo.name :"";
        //   },},
        { prop: "organName", label: "归属部门" },
        { prop: "positionsName", label: "职位" },
        // {
        //   prop: "itemsSum",
        //   label: "点检项",
        //   slotName: "items-sum",
        //   minWidth: 180,
        // },
        { prop: "userName", label: "登陆账号" },
        {
          prop: "userType",
          label: "账号类别",

          slotName: "userType"
        },
        {
          prop: "createdTime",
          label: "创建时间",
          minWidth: 180
          //  slotName: "createdTime",
        },
        {
          prop: "enable",
          label: "帐号状态",

          slotName: "enable"
        },
        {
          prop: "operate",
          label: "操作",
          minWidth: 240,
          slotName: "operate-column",
          fixed: "right"
        }
      ],
      tableData: []
    };
  },

  watch: {
    formChange: () => {}
  },
  computed: {
    ...mapState(["system_username", "app"])
  },
  created() {
    //初始获取几个基本数据,分别为操作状态,按钮权限等
    (this.formOptions.forms = this.formOptions.forms.map(e => {
      const key = e.prop;
      const data = this.$store.state.system_username.listSearchParams;
      e.defaultValue = data[key] || "";
      return e;
    })),
      //this.submitHandler=this.searchWithParams
      this.$store
        .dispatch(this.$store_url_button, {
          add: this.add,
          export: this.export,
          delete: this.delete,
          edit: this.edit,
          detail: this.detail,
          using: this.using,
          useless: this.useless,
          downloadTemplete: this.downloadTemplete,
          downloadIdentify: this.downloadIdentify,
          resetPwd: this.resetPwd
        })
        .then(async () => {
          const department = listTotree(
            this.$store.state.app.allCode.department
          );
          const allDuty = this.$store.state.app.allDuty;
          this.$set(this.formOptions.forms[3], "options", department);
          this.$set(this.formOptions.forms[4], "options", allDuty);
          this.getList(); // 表格数据
        });

    // this.listQuery=this.$store.state.basicEquipment.listSearchParams||{}  //操作状态
  },
  methods: {
    cancel() {
      this.dialogFormVisible = false;
    },
    dialogSubmit() {
      this.$refs["ruleForm"].validate(valid => {
        if (valid) {
          if (this.ruleForm && this.ruleForm.userType) {
            this.ruleForm.userType = this.ruleForm.userType.toString();
          }

          this.$store
            .dispatch("system_username/saveInfo", this.ruleForm)
            .then(res => {
              this.getList();
              this.dialogFormVisible = false;
            })
            .catch(err => {});
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //自定义该业务模块下的按钮方法
    using(row) {
      this.$confirm(`确认启用该账号?`, "启用账号", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$store
            .dispatch("system_username/useUserInfo", row.id)
            .then(res => {
              this.getList();
              //this.dialogFormVisible=false
            })
            .catch(err => {});
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消启用"
          });
        });
    },
    useless(row) {
      this.$confirm(
        `确认停用该账号?
      停用后该账号将不可使用`,
        "停用账号",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(() => {
          this.$store
            .dispatch("system_username/uselessUserInfo", row.id)
            .then(res => {
              this.getList();
            })
            .catch(err => {});
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消停用"
          });
        });
    },

    add(row) {
      this.ruleForm = {};
      this.showPwd = true;
      this.dialogFormVisible = true;
    },
    edit(row) {
      console.log(row, "++++row++++");

      this.ruleForm = row;
      this.showPwd = false;
      this.dialogFormVisible = true;
    },
    downloadIdentify(row) {
      console.log("下载设备标识卡");
      this.dialogFormVisible = true;
    },
    async downloadTemplete(ids) {
      console.log("下载导出模板");
      const download = await this.$store.dispatch(
        "system_username/downloadTemplete"
      );
      //window.open(download.)
      console.log(download);
    },
    resetPwd(row) {
      console.log(row);
      this.$confirm(
        `确认重置密码？
临时密码将以短信形式发送至该账号绑定手机`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(() => {
          this.$store
            .dispatch("system_username/resetPwd", row.id)
            .then(response => {
              this.$message({
                type: "success",
                message: "重置成功!"
              });
              this.getList();
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "重置失败"
              });
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消重置"
          });
        });
    },
    delete(row) {
      console.log(row, "+++delete row++");
      this.$confirm(
        `该账号删除后不可恢复，确认删除？请先确保：
        1.该账号无审批任务
        2.该账号不在任一审批配置中`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(() => {
          this.$store
            .dispatch("system_username/deleteDeviceInfo", row.id)
            .then(response => {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              this.getList();
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "删除失败"
              });
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    update() {},
    detail(row) {
      console.log(row);

      localStorage.setItem("/device-basic/component/detail/index", row.id);
      this.$router.push("/device-basic/component/detail/index");
    },
    import() {},
    export() {
      console.log("导出");
      this.$store.dispatch("system_username/exportFile");
    },
    //弹窗的关闭
    cancel() {
      console.log("关闭弹窗");
      this.dialogFormVisible = false;
    },
    //更新弹窗数据
    updateDialog() {
      console.log("更新并关闭弹窗");
      this.dialogFormVisible = false;
    },
    //搜索按钮
    searchWithParams() {
      console.log("搜索");
    },
    async getList(args) {
      // this.listLoading = true
      console.log(args);
      await this.$store.dispatch("system_username/requestDeviceList", args);
      this.paginationInfo.total = this.$store.state.system_username.total;
    },
    handleFilter(args) {
      this.listQuery.page = 1;
      this.getList(args);
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: "操作成功",
        type: "success"
      });
      row.status = status;
    },
    sortChange(data) {
      const { prop, order } = data;
      if (prop === "id") {
        this.sortByID(order);
      }
    },
    sortByID(order) {
      if (order === "ascending") {
        this.listQuery.sort = "+id";
      } else {
        this.listQuery.sort = "-id";
      }
      this.handleFilter();
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: "",
        timestamp: new Date(),
        title: "",
        status: "published",
        type: ""
      };
    },
    handleCreate() {
      // this.resetTemp();
      // this.dialogStatus = "create";
      // this.dialogFormVisible = true;
      // this.$nextTick(() => {
      //   this.$refs["dataForm"].clearValidate();
      // });
      this.dialogFormVisible = true;
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row); // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp);
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    handleDelete(row) {
      this.$notify({
        title: "成功",
        message: "删除成功",
        type: "success",
        duration: 2000
      });
      const index = this.list.indexOf(row);
      this.list.splice(index, 1);
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    }
  }
};
</script>
